package com.lzk.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lzk.sys.entity.User;
import com.lzk.sys.mapper.UserMapper;
import com.lzk.sys.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MissLzk
 * @since 2023-09-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public Map<String, Object> login(User user) {
        // 根据用户名 和 密码查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        wrapper.eq(User::getPassword,user.getPassword());
        User loginuser = this.baseMapper.selectOne(wrapper);

        // 结果不为空 则生成token 并且将用户信息存入redis
        if (loginuser != null){
            // 暂时用UUID  终极方案是jwt
            String key = "user : " +  UUID.randomUUID();
            //存入redis
            loginuser.setPassword(null);
            redisTemplate.opsForValue().set(key,loginuser,30, TimeUnit.MINUTES);

            //返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token",key);
            return data;
        }
        return null;
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        // 根据token 获取用户信息
        Object obj = redisTemplate.opsForValue().get(token);
        if (obj != null){
            User loginUser =  JSON.parseObject(JSON.toJSONString(obj),User.class);
            Map<String, Object> data = new HashMap<>();
            data.put("name",loginUser.getUsername());
            data.put("avatar",loginUser.getAvatar());

            //角色
            data.put("roles","员工");
            return data;
        }
        return null;

    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(token);
    }


}
